/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */

var length = function(head){
    let len = 0;
    while (head != null) {
        len++;
        head = head.next;
    }
    return len;
}
/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 * //统计总数 计算出要删除node的index 再进行删除操作
 */
var removeNthFromEnd = function(head, n) {
    let pre = head;
    const last = length(head) - n;
    //如果last等于0表示删除的是头结点
    if (last === 0)
        return head.next;
    //这里首先要找到要删除链表的前一个结点
    for (let i = 0; i < last - 1; i++) {
        pre = pre.next;
    }
    //然后让前一个结点的next指向要删除节点的next
    pre.next = pre.next.next;
    return head;
};

function ListNode(val, next) {
    this.val = (val===undefined ? 0 : val)
    this.next = (next===undefined ? null : next)
}

/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 * //统计总数 计算出要删除node的index 再进行删除操作
 */
var removeNthFromEnd = function(head, n) {
    let fast = head;
    let slow = head;
    //fast先移动n位 此时fast和slow的区间为n
    for (let i = 0; i < n; i++) {
        fast = fast.next;
    }
    if (!fast)
        return head.next;

    while (fast.next!==null){
        fast = fast.next;
        slow = slow.next;
    }

    //当fast为尾节点的时候就 slow就是当前倒数n+1的节点 然后将slow的下个节点删除即可
    slow.next = slow.next.next;
    return head;
};
console.log(removeNthFromEnd(new ListNode(1),1));